package top.pcat.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import top.pcat.GateWayMain;
import top.pcat.util.ProtostuffUtils;

@Slf4j
public class GateWayServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            System.out.println("msg的真实类型" + msg.getClass());
            System.out.println("客服端地址" + ctx.channel().remoteAddress());

            String address = GateWayMain.getAddress();
            byte[] serialize = ProtostuffUtils.serialize(address);

            ByteBuf buf = Unpooled.wrappedBuffer(serialize);

            // 构造一个http响应体，即HttpResponse
            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            // 设置响应头信息
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream");
            defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

            // 将响应体写入到通道中
            ctx.writeAndFlush(defaultFullHttpResponse);

        }
    }

}

